<template>
  <div class="analysis-container">
    <!-- 顶部统计卡片 -->
    <a-row :gutter="16" class="stats-row">
      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic
            title="总访问量"
            :value="statsData.totalVisits"
            :value-style="{ color: '#165dff' }"
          >
            <template #prefix>
              <icon-eye />
            </template>
          </a-statistic>
          <div class="stat-trend">
            <span class="trend-text">较昨日</span>
            <span class="trend-value up">+12.5%</span>
          </div>
        </a-card>
      </a-col>

      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic
            title="新增用户"
            :value="statsData.newUsers"
            :value-style="{ color: '#00b42a' }"
          >
            <template #prefix>
              <icon-user-add />
            </template>
          </a-statistic>
          <div class="stat-trend">
            <span class="trend-text">较昨日</span>
            <span class="trend-value up">+8.2%</span>
          </div>
        </a-card>
      </a-col>

      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic
            title="销售额"
            :value="statsData.revenue"
            :value-style="{ color: '#ff7d00' }"
          >
            <template #prefix>
              <icon-euro />
            </template>
          </a-statistic>
          <div class="stat-trend">
            <span class="trend-text">较昨日</span>
            <span class="trend-value down">-2.1%</span>
          </div>
        </a-card>
      </a-col>

      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic
            title="订单数量"
            :value="statsData.orders"
            :value-style="{ color: '#7816f7' }"
          >
            <template #prefix>
              <icon-file />
            </template>
          </a-statistic>
          <div class="stat-trend">
            <span class="trend-text">较昨日</span>
            <span class="trend-value up">+5.4%</span>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 图表区域 -->
    <a-row :gutter="16" class="charts-row">
      <!-- 访问量趋势图 -->
      <a-col :span="16">
        <a-card title="访问量趋势" class="chart-card">
          <div ref="visitTrendRef" class="chart-container"></div>
        </a-card>
      </a-col>

      <!-- 用户分布饼图 -->
      <a-col :span="8">
        <a-card title="用户来源分布" class="chart-card">
          <div ref="userSourceRef" class="chart-container"></div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16" class="charts-row">
      <!-- 销售数据柱状图 -->
      <a-col :span="12">
        <a-card title="月度销售额" class="chart-card">
          <div ref="salesChartRef" class="chart-container"></div>
        </a-card>
      </a-col>

      <!-- 实时数据 -->
      <a-col :span="12">
        <a-card title="实时数据" class="chart-card">
          <div class="realtime-data">
            <div class="data-item">
              <div class="data-label">在线用户</div>
              <div class="data-value">{{ realtimeData.onlineUsers }}</div>
            </div>
            <div class="data-item">
              <div class="data-label">今日订单</div>
              <div class="data-value">{{ realtimeData.todayOrders }}</div>
            </div>
            <div class="data-item">
              <div class="data-label">系统负载</div>
              <div class="data-value">
                <a-progress :percent="realtimeData.systemLoad" size="small" />
              </div>
            </div>
            <div class="data-item">
              <div class="data-label">内存使用率</div>
              <div class="data-value">
                <a-progress 
                  :percent="realtimeData.memoryUsage" 
                  size="small"
                  :color="realtimeData.memoryUsage > 80 ? '#f53f3f' : '#00b42a'"
                />
              </div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 数据表格 -->
    <a-row :gutter="16" class="table-row">
      <a-col :span="24">
        <a-card title="最新订单" class="table-card">
          <a-table 
            :columns="orderColumns" 
            :data="orderData" 
            :pagination="false"
            size="small"
          >
            <template #status="{ record }">
              <a-tag 
                :color="getStatusColor(record.status)"
              >
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            
            <template #amount="{ record }">
              ¥{{ record.amount.toLocaleString() }}
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

// 图表引用
const visitTrendRef = ref()
const userSourceRef = ref()
const salesChartRef = ref()

// 统计数据
const statsData = reactive({
  totalVisits: 128690,
  newUsers: 1856,
  revenue: 45678,
  orders: 2341
})

// 实时数据
const realtimeData = reactive({
  onlineUsers: 1247,
  todayOrders: 156,
  systemLoad: 65,
  memoryUsage: 72
})

// 订单表格配置
const orderColumns = [
  { title: '订单号', dataIndex: 'orderNo', width: 120 },
  { title: '客户', dataIndex: 'customer', width: 120 },
  { title: '商品', dataIndex: 'product', width: 200 },
  { title: '金额', slotName: 'amount', width: 100 },
  { title: '状态', slotName: 'status', width: 100 },
  { title: '时间', dataIndex: 'createTime', width: 160 }
]

// 订单数据
const orderData = ref([
  {
    orderNo: 'ORDER001',
    customer: '张三',
    product: 'MacBook Pro 16寸',
    amount: 19999,
    status: 'paid',
    createTime: '2024-01-01 10:30:00'
  },
  {
    orderNo: 'ORDER002',
    customer: '李四',
    product: 'iPhone 15 Pro',
    amount: 7999,
    status: 'pending',
    createTime: '2024-01-01 09:15:00'
  },
  {
    orderNo: 'ORDER003',
    customer: '王五',
    product: 'iPad Air',
    amount: 4799,
    status: 'shipped',
    createTime: '2024-01-01 08:45:00'
  }
])

// 图表实例
let visitTrendChart: echarts.ECharts
let userSourceChart: echarts.ECharts
let salesChart: echarts.ECharts

// 状态相关方法
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    paid: 'green',
    pending: 'orange',
    shipped: 'blue',
    cancelled: 'red'
  }
  return colorMap[status] || 'gray'
}

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    paid: '已支付',
    pending: '待支付',
    shipped: '已发货',
    cancelled: '已取消'
  }
  return textMap[status] || '未知'
}

// 初始化访问量趋势图
const initVisitTrendChart = () => {
  visitTrendChart = echarts.init(visitTrendRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['访问量', '独立访客']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '访问量',
        type: 'line',
        stack: 'Total',
        data: [1200, 1320, 1010, 1340, 1290, 1330, 1320],
        smooth: true,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(22, 93, 255, 0.3)' },
            { offset: 1, color: 'rgba(22, 93, 255, 0.1)' }
          ])
        }
      },
      {
        name: '独立访客',
        type: 'line',
        stack: 'Total',
        data: [820, 932, 901, 934, 1290, 1330, 1320],
        smooth: true,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(0, 180, 42, 0.3)' },
            { offset: 1, color: 'rgba(0, 180, 42, 0.1)' }
          ])
        }
      }
    ]
  }
  
  visitTrendChart.setOption(option)
}

// 初始化用户来源饼图
const initUserSourceChart = () => {
  userSourceChart = echarts.init(userSourceRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '访问来源',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 1048, name: '搜索引擎' },
          { value: 735, name: '直接访问' },
          { value: 580, name: '邮件营销' },
          { value: 484, name: '联盟广告' },
          { value: 300, name: '视频广告' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  userSourceChart.setOption(option)
}

// 初始化销售数据柱状图
const initSalesChart = () => {
  salesChart = echarts.init(salesChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月'],
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'bar',
        barWidth: '60%',
        data: [1200, 2000, 1500, 8000, 7000, 2300, 1900],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#ff7d00' },
            { offset: 1, color: '#ffb84d' }
          ])
        }
      }
    ]
  }
  
  salesChart.setOption(option)
}

// 窗口大小改变时重新调整图表
const handleResize = () => {
  visitTrendChart?.resize()
  userSourceChart?.resize()
  salesChart?.resize()
}

// 实时数据更新
const updateRealtimeData = () => {
  // 模拟实时数据更新
  realtimeData.onlineUsers = Math.floor(Math.random() * 500) + 1000
  realtimeData.todayOrders = Math.floor(Math.random() * 50) + 100
  realtimeData.systemLoad = Math.floor(Math.random() * 40) + 40
  realtimeData.memoryUsage = Math.floor(Math.random() * 30) + 50
}

let timer: NodeJS.Timeout

onMounted(() => {
  // 初始化图表
  setTimeout(() => {
    initVisitTrendChart()
    initUserSourceChart()
    initSalesChart()
  }, 100)
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
  
  // 启动实时数据更新
  timer = setInterval(updateRealtimeData, 5000)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  visitTrendChart?.dispose()
  userSourceChart?.dispose()
  salesChart?.dispose()
  clearInterval(timer)
})
</script>

<style lang="scss" scoped>
.analysis-container {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  .stat-trend {
    margin-top: 8px;
    font-size: 12px;
    
    .trend-text {
      color: #86909c;
    }
    
    .trend-value {
      margin-left: 8px;
      font-weight: 500;
      
      &.up {
        color: #00b42a;
      }
      
      &.down {
        color: #f53f3f;
      }
    }
  }
}

.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  .chart-container {
    height: 300px;
  }
}

.realtime-data {
  .data-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
    border-bottom: 1px solid #f2f3f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .data-label {
      color: #86909c;
      font-size: 14px;
    }
    
    .data-value {
      font-size: 16px;
      font-weight: 500;
      color: #1d2129;
      min-width: 80px;
      text-align: right;
    }
  }
}

.table-row {
  margin-bottom: 20px;
}

.table-card {
  :deep(.arco-table-th) {
    background-color: #f7f8fa;
  }
}
</style> 